import { unref, computed } from 'vue';
import type { ComputedRef, Slots, Ref } from 'vue';
import type { BasicTableProps, FetchParams } from '../types/table';
import type { FormProps } from '#/Form';
import { isFunction } from '@/utils/is';
import { TableForm } from '../types/tableForm';

export function useTableForm(
	propsRef: ComputedRef<BasicTableProps>,
	slots: Slots,
	fetch: (opt?: FetchParams | undefined) => Promise<void>,
	getLoading: ComputedRef<boolean | undefined>,
	filteredInfo: Ref<Recordable | undefined>,
) {
	const getFormProps = computed((): Partial<FormProps & TableForm> => {
		const { formConfig, resetWithTableSearchInfo } = unref(propsRef);

		const { submitButtonOptions, showAdvancedButton = false } = formConfig || {};
		return {
			resetWithTableSearchInfo,
			filteredInfo,
			showAdvancedButton: showAdvancedButton,
			...formConfig,
			submitButtonOptions: { loading: unref(getLoading), ...submitButtonOptions },
			compact: true,
		};
	});

	const getFormSlotKeys: ComputedRef<string[]> = computed(() => {
		const keys = Object.keys(slots);
		return keys.map(item => (item.startsWith('form-') ? item : null)).filter(item => !!item) as string[];
	});

	function replaceFormSlotKey(key: string) {
		if (!key) return '';
		return key?.replace?.(/form\-/, '') ?? '';
	}

	function handleSearchInfoChange(info: Recordable) {
		const { handleSearchInfoFn } = unref(propsRef);
		if (handleSearchInfoFn && isFunction(handleSearchInfoFn)) {
			info = handleSearchInfoFn(info) || info;
		}
		fetch({ searchInfo: info, page: 1 });
	}

	function handleKeyWordInfoChange(info: Recordable) {
		const { handleKeyWordInfoFn } = unref(propsRef);
		if (handleKeyWordInfoFn && isFunction(handleKeyWordInfoFn)) {
			info = handleKeyWordInfoFn(info) || info;
		}
		fetch({ keyWordInfo: info, page: 1 });
	}

	return {
		getFormProps,
		replaceFormSlotKey,
		getFormSlotKeys,
		handleSearchInfoChange,
		handleKeyWordInfoChange,
	};
}
